import Vue from 'vue';
import store from '@/store';
let req = null; //用于中断请求
const httpRequest = (opts) => {
	const baseUrl = store.state.baseUrl + '/appData';
	let httpDefaultOpts = {
		url: opts.url.indexOf('http'||'https') != -1 ? opts.url : baseUrl + opts.url,
		data: opts.data ? {...opts.data}:{},
		method: opts.methods,
		timeout: 10*1000,
		header: opts.methods == 'get' ? {
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		} : {
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		},
		dataType: opts.dataType ? opts.dataType: 'json',
	}
	// 判断token存在
	if(store.state.token){
		httpDefaultOpts.header['token'] = store.state.token
	}
	if(opts.method == 'get'){
		httpDefaultOpts.data = {
			...{ '_t': new Date().getTime() },
			...data
		}
	}
	let instenceToast = null;
	if(req && opts.abort){
		req.abort()
	}
	let promise = new Promise(function(resolve, reject) {
		req = uni.request({
			...httpDefaultOpts,
			success: function(res){
				req = null;
				if(typeof(res.data) == "string" ) return resolve(null);
				// 801 无token
				if(res.data.code == 801){
					resolve(res);
					return uni.showModal({
						title: "提示",
						content: res.data.message,
						success(res) {
							if(res.confirm){
								uni.reLaunch({
									url:'/pages/login/login'
								})
							}
						}
					})
				}
				// 302 token为空， 304 token过期
				if(res.data.statusCode == 304 || res.data.statusCode == 302){
					reject(res);
					return	uni.showModal({
									title: "提示",
									content: "身份信息过期，请重新登录,code:"+res.data.statusCode,
									showCancel: true,
									success:(res)=>{
										if(res.confirm){
											store.dispatch('loginOut').then(()=>{
												uni.reLaunch({
													url:"/pages/login/login"
												})
											}).catch(()=>{
												uni.showModal({
													title:"提示",
													content:"退出失败"
												})
											})
										}
										if(res.cancel){
											
										}
									}
								})
				}
				if(res.data.statusCode && res.data.statusCode!== 200){
					uni.showModal({
						title: "提示",
						content: res.data.errorCode,
						showCancel: false
					})
				}
				resolve(res)
				// if(res.length == 1){
				// 	if(res[0] && res[0].errMsg){
				// 		resolve(null)
				// 	}
				// }else{
				// 	if(typeof(res[1].data)=='string'){
				// 		resolve(null)
				// 	}else{
				// 		resolve(res[1])
				// 	}
				// }
			},
			fail:function(response){
				req = null;
				reject(response)
				if(response.errMsg.indexOf("request:fail") != -1 && !opts.abort){
					return uni.showToast({
						title:"服务器请求失败",
						icon:"none"
					})
				}
			}
		})
	})
	return promise
};
export default {
	// baseUrl,
	httpRequest
}